
#include <stdio.h>
#include "http.h"
#include "url.h"

int main (int argc, char *argv[]) {
	HTTP_header_t	*http_hdr = NULL;
	URL_t	*url = NULL;
	int fd = -1;
	int redirect = 0;
	int auth_retry=0;
	int seekable=0;
	char *content_type;
	char *next_url;
	
	if (argc < 2) {
		printf("Usage: %s  url [username] [passwd]\n", argv[0]);
		return 1;
	}
	
	url = url_new(argv[1]);
	if (url == NULL) {
		printf("Get url failed.\n");
		return 1;
	}
	if (argc == 4) {
		url->username = argv[2];
		url->password = argv[3];
	}
	do {
		redirect = 0;
		if (fd > 0) closesocket(fd);
		fd = http_send_request(url, 0);
		if (fd < 0) {
			printf("send request error.\n");
			goto err_out;
		}
		http_free(http_hdr);
		http_hdr =(HTTP_header_t*) http_read_response(fd);
		if (http_hdr == NULL) {
			printf("read responese error.\n");
			goto err_out;
		}
		
		http_debug_hdr(http_hdr);
		 // Check if we can make partial content requests and thus seek in http-streams
		if( http_hdr!=NULL && http_hdr->status_code==200 ) { 
			char *accept_ranges;
			if( (accept_ranges = http_get_field(http_hdr,"Accept-Ranges")) != NULL )
				seekable = strncmp(accept_ranges,"bytes",5)==0;
		}   
		switch(http_hdr->status_code) {
			case 200: // ok
				content_type = http_get_field( http_hdr, "Content-Type" );
				if (content_type != NULL) {
					char *content_length = NULL;
					printf("Content-Type: [%s]\n", content_type);
					if( (content_length = http_get_field(http_hdr, "Content-Length")) != NULL) {
						printf("Content-Length: [%s]\n", http_get_field(http_hdr, "Content-Length"));
					}
				}
				printf("Server returned %d: %s\n", http_hdr->status_code, http_hdr->reason_phrase);
			break;
			case 301: // Permanently
			case 302: // Temporarily
			case 303: // See Other
				next_url = http_get_field( http_hdr, "Location" );
				if (next_url != NULL) {
					url_redirect( &url, next_url );
					printf("Next: [%s]\n", next_url);
				}
			break;
			case 401: // Authentication required
				if( http_authenticate(http_hdr, url, &auth_retry)<0 )
					goto err_out;
			break;
			default:
				printf("Server returned %d: %s\n", http_hdr->status_code, http_hdr->reason_phrase);
		}		
	} while (redirect);
	
	return 0;
err_out:
	if(fd >0 ) closesocket(fd);
	fd = -1;
	http_free(http_hdr);
	http_hdr = NULL;
	return -1;
}
